import { Command } from 'commander'
import { readFileSync } from 'fs'
import shell from 'shelljs'
import path from 'path'
import rimraf from 'rimraf'

// 检测当前环境是否有yalc命令
if (!shell.which('yalc')) {
  shell.echo('抱歉执行该脚本需要 yalc')
  shell.exit(1)
}

/**
 * 从package.json中获取version值
 *
 * @return  {[type]}  [return description]
 */
function loadVersionFromPackageJson() {
  const jsonStr = readFileSync('./package.json', 'utf-8')
  const jsonObj = JSON.parse(jsonStr)
  return jsonObj.version
}

const program = new Command('yalc-clean')
program.usage('yalc仓库包名 [-y]')
program.description('用于删除yalc仓库中的包')
program.option('-y --yes', '不再询问，所有询问填Y,然后直接删除yalc仓库的包')

program.version(loadVersionFromPackageJson(), '-v, --version', '输出当前版本')
program.helpOption('-h --help', '显示命令帮助信息')

program.parse(process.argv)

function executeYalcDir(sucCall) {
  shell.exec('yalc dir', function (code, stdout, stderr) {
    const yalcRepo = stdout.replace('\n', '').replace('\r\n', '')
    if (!yalcRepo) {
      shell.echo(`执行出错:未获取到yalc仓库地址`)
      shell.exit(1)
    }
    if (code === 0) {
      sucCall && sucCall(yalcRepo)
    } else {
      shell.echo(`执行出错:${stderr}`)
      shell.exit(1)
    }
  })
}

function executeYalcInstallationsShow(yalcPackageName, sucCall) {
  shell.exec(
    `yalc installations show ${yalcPackageName}`,
    function (code, stdout, stderr) {
      if (code === 0) {
        stdout && shell.echo(stdout)
        sucCall && sucCall()
      } else {
        shell.echo(`执行出错:${stderr}`)
      }
    }
  )
}

function executeYalcInstallationsClean(yalcPackageName, sucCall) {
  shell.exec(
    `yalc installations clean ${yalcPackageName}`,
    function (code, stdout, stderr) {
      if (code === 0) {
        stdout && shell.echo(stdout)
        sucCall && sucCall()
      } else {
        shell.echo(`执行出错:${stderr}`)
      }
    }
  )
}

function main() {
  const yalcPackageName = program.args[0]
  if (!yalcPackageName) return

  executeYalcDir(yalcRepo => {
    executeYalcInstallationsShow(yalcPackageName, () => {
      executeYalcInstallationsClean(yalcPackageName, () => {
        const packageFullDir = path.resolve(
          yalcRepo,
          'packages',
          yalcPackageName
        )
        console.log(packageFullDir)
        rimraf(packageFullDir, error => {
          if (error) {
            console.log(error)
          }
        })
      })
    })
  })
}

main()
